{% extends 'dashboard/base.html' %}

{% block title %}用户管理 - 巧巧点餐管理后台{% endblock %}

{% block content %}
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">用户管理</h1>
    <a href="{% url 'dashboard:user_add' %}" class="btn btn-primary btn-sm">
        <i class="fas fa-plus fa-sm"></i> 添加用户
    </a>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">筛选条件</h6>
    </div>
    <div class="card-body">
        <!-- 搜索和筛选 -->
        <form method="get" class="search-form">
            <div class="row">
                <div class="col-md-4 mb-2">
                    <div class="form-group mb-2">
                        <label for="search" class="small">搜索用户</label>
                        <input type="text" id="search" name="search" class="form-control" value="{{ request.GET.search|default:'' }}" placeholder="用户名/姓名/手机号...">
                    </div>
                </div>
                <div class="col-md-4 mb-2">
                    <div class="form-group mb-2">
                        <label for="role" class="small">用户角色</label>
                        <select id="role" name="role" class="form-control">
                            <option value="">所有角色</option>
                            <option value="admin" {% if request.GET.role == 'admin' %}selected{% endif %}>管理员</option>
                            <option value="staff" {% if request.GET.role == 'staff' %}selected{% endif %}>员工</option>
                            <option value="customer" {% if request.GET.role == 'customer' %}selected{% endif %}>顾客</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4 mb-2">
                    <div class="form-group mb-2">
                        <label for="is_active" class="small">状态</label>
                        <select id="is_active" name="is_active" class="form-control">
                            <option value="">所有状态</option>
                            <option value="active" {% if request.GET.is_active == 'active' %}selected{% endif %}>启用</option>
                            <option value="inactive" {% if request.GET.is_active == 'inactive' %}selected{% endif %}>禁用</option>
                        </select>
                    </div>
                </div>
                <div class="col-12 mb-2 d-flex justify-content-end">
                    <div class="form-group mb-2 d-flex">
                        <button type="submit" class="btn btn-primary btn-sm mr-2">
                            <i class="fas fa-search fa-sm"></i> 搜索
                        </button>
                        <a href="{% url 'dashboard:user_list' %}" class="btn btn-light btn-sm">
                            <i class="fas fa-redo fa-sm"></i> 重置
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 用户列表 -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">用户列表</h6>
        <div class="btn-group">
            <button type="button" class="btn btn-sm btn-outline-secondary" id="selectAllBtn">
                <i class="fas fa-check-square fa-sm"></i> 全选
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="batchEnableBtn" disabled>
                <i class="fas fa-check fa-sm"></i> 批量启用
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="batchDisableBtn" disabled>
                <i class="fas fa-times fa-sm"></i> 批量禁用
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th width="5%">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="selectAll">
                                <label class="custom-control-label" for="selectAll"></label>
                            </div>
                        </th>
                        <th width="5%">#</th>
                        <th width="15%">用户名</th>
                        <th width="15%">姓名</th>
                        <th width="15%">手机号</th>
                        <th width="10%">角色</th>
                        <th width="10%">状态</th>
                        <th width="25%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% if users %}
                        {% for user in users %}
                        <tr data-user-id="{{ user.id }}">
                            <td>
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input user-checkbox" id="user-{{ user.id }}" value="{{ user.id }}">
                                    <label class="custom-control-label" for="user-{{ user.id }}"></label>
                                </div>
                            </td>
                            <td>{{ user.id }}</td>
                            <td class="text-truncate" style="max-width: 150px;">
                                {{ user.username }}
                                {% if user.is_superuser %}
                                <span class="badge badge-secondary">超级管理员</span>
                                {% endif %}
                            </td>
                            <td>{{ user.first_name }} {{ user.last_name }}</td>
                            <td>{{ user.phone|default:'--' }}</td>
                            <td>
                                {% if user.is_superuser or user.role == 'admin' %}
                                    <span class="badge badge-primary">管理员</span>
                                {% elif user.role == 'staff' %}
                                    <span class="badge badge-info">员工</span>
                                {% else %}
                                    <span class="badge badge-secondary">顾客</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if user.is_active %}
                                    <span class="badge badge-success">启用</span>
                                {% else %}
                                    <span class="badge badge-danger">禁用</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="btn-group">
                                    <a href="{% url 'dashboard:user_edit' user_id=user.id %}" class="btn btn-info btn-sm">
                                        <i class="fas fa-edit fa-sm"></i> 编辑
                                    </a>
                                    {% if user.is_active %}
                                    <button type="button" class="btn btn-warning btn-sm status-btn" 
                                            data-toggle="modal" data-target="#statusModal" 
                                            data-id="{{ user.id }}" 
                                            data-action="disable"
                                            data-username="{{ user.username }}">
                                        <i class="fas fa-ban fa-sm"></i> 禁用
                                    </button>
                                    {% else %}
                                    <button type="button" class="btn btn-success btn-sm status-btn" 
                                            data-toggle="modal" data-target="#statusModal" 
                                            data-id="{{ user.id }}" 
                                            data-action="enable"
                                            data-username="{{ user.username }}">
                                        <i class="fas fa-check-circle fa-sm"></i> 启用
                                    </button>
                                    {% endif %}
                                    
                                    {% if not user.is_superuser %}
                                    <button type="button" class="btn btn-danger btn-sm delete-btn" 
                                            data-toggle="modal" data-target="#deleteModal" 
                                            data-id="{{ user.id }}" 
                                            data-username="{{ user.username }}">
                                        <i class="fas fa-trash fa-sm"></i> 删除
                                    </button>
                                    {% endif %}
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="8" class="text-center py-4">暂无用户数据</td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        {% if users.has_other_pages %}
        <div class="mt-4">
            <nav aria-label="分页导航">
                <ul class="pagination justify-content-center">
                    {% if users.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ users.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="上一页">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link" aria-hidden="true">&laquo;</span>
                    </li>
                    {% endif %}

                    {% for i in users.paginator.page_range %}
                        {% if users.number == i %}
                        <li class="page-item active">
                            <span class="page-link">{{ i }}</span>
                        </li>
                        {% elif i > users.number|add:'-3' and i < users.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ i }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">{{ i }}</a>
                        </li>
                        {% endif %}
                    {% endfor %}

                    {% if users.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ users.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="下一页">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link" aria-hidden="true">&raquo;</span>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
        {% endif %}
    </div>
</div>

<!-- 状态更新模态框 -->
<div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="statusModalLabel">更新用户状态</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p id="statusMessage">您确定要对用户 <strong id="statusUsername"></strong> 执行此操作吗？</p>
            </div>
            <div class="modal-footer">
                <form id="statusForm" method="post" action="">
                    {% csrf_token %}
                    <input type="hidden" id="statusAction" name="action" value="">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" id="statusSubmitBtn" class="btn btn-primary">确认</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>您确定要删除用户 <strong id="deleteUsername"></strong> 吗？</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle mr-1"></i> 此操作不可逆，删除后将无法恢复用户数据。</p>
            </div>
            <div class="modal-footer">
                <form id="deleteForm" method="post" action="">
                    {% csrf_token %}
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-danger">确认删除</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 批量状态更新模态框 -->
<div class="modal fade" id="batchModal" tabindex="-1" role="dialog" aria-labelledby="batchModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="batchModalLabel">批量操作确认</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p id="batchMessage">您确定要对所选用户执行此操作吗？</p>
            </div>
            <div class="modal-footer">
                <form id="batchForm" method="post" action="{% url 'dashboard:user_batch_action' %}">
                    {% csrf_token %}
                    <input type="hidden" id="batchAction" name="action" value="">
                    <input type="hidden" id="selectedUsers" name="user_ids" value="">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">确认</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 状态更新模态框
        $('#statusModal').on('show.bs.modal', function (event) {
            const button = $(event.relatedTarget);
            const userId = button.data('id');
            const username = button.data('username');
            const action = button.data('action');
            
            $('#statusUsername').text(username);
            $('#statusAction').val(action);
            $('#statusForm').attr('action', '/dashboard/users/status/' + userId + '/');
            
            if (action === 'enable') {
                $('#statusMessage').html('您确定要<strong class="text-success">启用</strong>用户 <strong>' + username + '</strong> 吗？');
                $('#statusSubmitBtn').removeClass('btn-warning').addClass('btn-success').text('确认启用');
            } else {
                $('#statusMessage').html('您确定要<strong class="text-warning">禁用</strong>用户 <strong>' + username + '</strong> 吗？');
                $('#statusSubmitBtn').removeClass('btn-success').addClass('btn-warning').text('确认禁用');
            }
        });
        
        // 删除确认模态框
        $('#deleteModal').on('show.bs.modal', function (event) {
            const button = $(event.relatedTarget);
            const userId = button.data('id');
            const username = button.data('username');
            
            $('#deleteUsername').text(username);
            $('#deleteForm').attr('action', '/dashboard/users/delete/' + userId + '/');
        });
        
        // 全选/取消全选
        $('#selectAll').on('change', function() {
            const isChecked = $(this).prop('checked');
            $('.user-checkbox').prop('checked', isChecked);
            updateBatchButtons();
        });
        
        $('#selectAllBtn').on('click', function() {
            const allChecked = $('.user-checkbox:checked').length === $('.user-checkbox').length;
            $('.user-checkbox').prop('checked', !allChecked);
            $('#selectAll').prop('checked', !allChecked);
            updateBatchButtons();
        });
        
        // 单个复选框变化事件
        $('.user-checkbox').on('change', function() {
            updateBatchButtons();
            
            // 更新全选复选框状态
            const totalCheckboxes = $('.user-checkbox').length;
            const checkedCheckboxes = $('.user-checkbox:checked').length;
            
            $('#selectAll').prop('checked', checkedCheckboxes === totalCheckboxes);
        });
        
        // 批量启用按钮事件
        $('#batchEnableBtn').on('click', function() {
            openBatchModal('enable', '启用');
        });
        
        // 批量禁用按钮事件
        $('#batchDisableBtn').on('click', function() {
            openBatchModal('disable', '禁用');
        });
        
        // 打开批量操作模态框
        function openBatchModal(action, actionText) {
            const selectedUsers = getSelectedUserIds();
            
            $('#batchAction').val(action);
            $('#selectedUsers').val(selectedUsers.join(','));
            $('#batchMessage').html('您确定要批量<strong>' + actionText + '</strong>所选的 <strong>' + selectedUsers.length + '</strong> 个用户吗？');
            
            $('#batchModal').modal('show');
        }
        
        // 获取所选用户ID
        function getSelectedUserIds() {
            const selectedIds = [];
            $('.user-checkbox:checked').each(function() {
                selectedIds.push($(this).val());
            });
            return selectedIds;
        }
        
        // 更新批量操作按钮状态
        function updateBatchButtons() {
            const selectedCount = $('.user-checkbox:checked').length;
            
            if (selectedCount > 0) {
                $('#batchEnableBtn, #batchDisableBtn').prop('disabled', false);
            } else {
                $('#batchEnableBtn, #batchDisableBtn').prop('disabled', true);
            }
        }
    });
</script>
{% endblock %} 